package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Cart;
import com.itheima.reggie.mapper.CartMapper;
import com.itheima.reggie.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;


    @Override
    public Cart save(Cart cartParam) {
        //1.根据用户id和套餐/菜品id判断当前表中是否有记录
        //菜品：select * from shopping_cart where user_id=#{} and dish_id=#{}
        //套餐：select * from shopping_cart where user_id=#{} and setmeal_id=#{}
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, UserHolder.get().getId());//设置登录用户id
        wrapper.eq(cartParam.getDishId() != null, Cart::getDishId, cartParam.getDishId());//菜品id
        wrapper.eq(cartParam.getSetmealId() != null, Cart::getSetmealId, cartParam.getSetmealId());//套餐id
        Cart cart = cartMapper.selectOne(wrapper);

        //2.判断是否存在菜品或者套餐，如果存在number+1，更新到数据库
        if (cart != null) {
            cart.setNumber(cart.getNumber() + 1);
            cartMapper.updateById(cart);
            return cart;
        } else {
            //3.如果不存在，将新的数据保存到数据库
            cartParam.setUserId(UserHolder.get().getId());
            cartParam.setNumber(1);
            cartParam.setCreateTime(new Date());
            cartMapper.insert(cartParam);
            return cartParam;
        }
    }

    @Override
    public Cart sub(Cart cartSub) {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, UserHolder.get().getId());//设置登录用户id
        wrapper.eq(cartSub.getDishId() != null, Cart::getDishId, cartSub.getDishId());//菜品id
        wrapper.eq(cartSub.getSetmealId() != null, Cart::getSetmealId, cartSub.getSetmealId());//套餐id
        Cart cart = cartMapper.selectOne(wrapper);
        cart.setNumber(cart.getNumber() - 1);

        if (cart.getNumber() <= 0) {
            cartMapper.delete(wrapper);

        } else {
            cartMapper.updateById(cart);

        }
        return cart;
    }

    @Override
    public List<Cart> findList() {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, UserHolder.get().getId());//设置登录用户id
        return cartMapper.selectList(wrapper);
    }

    @Override
    public void cleanList() {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, UserHolder.get().getId());//设置登录用户id
        cartMapper.delete(wrapper);
    }

}
